<?php

class Users extends Admin_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->helper('url');
        $this->load->model('users_model');
        $this->load->model('areas_model','areas');
    }
    //发送验证码给旧手机
    function send_old(){
        $post = $this->input->post();
        if (isset($post['tel'])){
            $usr = $this->db->where(array('tel'=>$post['tel']))->get("manager");
            if (!$usr->result_array()){
                $data['status'] = "fail";
                $data['msg'] = "手机号未注册!";
                $data['data'] = '';
                echo json_encode($data);exit;
            }
            $res = $this->send_code_general($post['tel']);
            if($res=="success"){
                $data['status'] = "success";
                $data['msg'] = "发送成功";
                $data['data'] = $this->config->item("code_session_id");
            }else{
                $data['status'] = "fail";
                $data['msg'] = $res;
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }

        echo json_encode($data);
    }

    //发送验证码给新手机
    function send_new(){
        $post = $this->input->post();
        if (isset($post['tel'])){
            $usr = $this->db->where(array('tel'=>$post['tel']))->get("manager");
            if ($usr->result_array()){
                $data['status'] = "fail";
                $data['msg'] = "手机号已注册!";
                $data['data'] = '';
                echo json_encode($data);exit;
            }
            $res = $this->send_code_general($post['tel']);
            if($res=="success"){
                $data['status'] = "success";
                $data['msg'] = "发送成功";
                $data['data'] = $this->config->item("code_session_id");
            }else{
                $data['status'] = "fail";
                $data['msg'] = $res;
                $data['data'] = "";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }

        echo json_encode($data);
    }
    //发送验证码
    function send(){
        $post = $this->input->post();
        if (isset($post['tel'])){
           $res = $this->send_code_general($post['tel']);
           if($res=="success"){
               $data['status'] = "success";
               $data['msg'] = "发送成功";
               $data['data'] = $this->config->item("code_session_id");
           }else{
               $data['status'] = "fail";
               $data['msg'] = $res;
               $data['data'] = "";
           }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        echo json_encode($data);
    }
    //发送短信验证码
    function send_code_general($tel=""){
        if(is_mobile($tel)){
            session_id($this->config->item("code_session_id"));
            session_start();
            if($rs = $_SESSION[$tel."code"]){
                $data = json_decode($rs,true);
                $minute=floor((time()-strtotime($data['time']))%86400/60);
                $code = generate_code();
                $msg  = "【文具1号】您的验证码为".$code."，请勿向他人泄露验证码。如非本人操作，请忽略。";
                // 重写发短信
                $this->load->library('message', '', 'mylib');
                $message_lib = $this->mylib;
                // end
                $res = $message_lib->send_msg($tel,$msg);
                if($res['status'] == 'success'){
                    $data1['time'] = date("Y-m-d H:i:s");
                    $data1['code'] = $code;
                    $_SESSION[$tel."code"] = json_encode($data1);
                    return "success";
                }else{
                    return "发送失败";
                }
            }else{
                $code = generate_code();
                $msg  = "【文具1号】您的验证码为".$code."，请勿向他人泄露验证码。如非本人操作，请忽略。";
                // 重写发短信
                $this->load->library('message', '', 'mylib');
                $message_lib = $this->mylib;
                // end
                $res = $message_lib->send_msg($tel,$msg);
                if($res['status'] == 'success'){
                    $data1['time'] = date("Y-m-d H:i:s");
                    $data1['code'] = $code;
                    $_SESSION[$tel."code"] = json_encode($data1);
                    return "success";
                }else{
                    return "发送失败";
                }
            }
        } else{
            return "请输入正确的手机号";
        }
    }

    /**  验证短信验证码
     * @param string $tel 手机号
     * @param string $code 输入验证码
     * @return bool
     */
    function confirm_code_gerenal($tel="",$code=""){
        session_id($this->config->item("code_session_id"));
        session_start();
        $rs = $_SESSION[$tel."code"];
        if($rs){
            $data = json_decode($rs,true);
            $minute=floor((time()-strtotime($data['time']))%86400/60);
            if($minute>5){
                return "此验证码已超过5分钟,已失效";
            }
            if($data['code'] == $code){
                return "success";
            }else{
                return "验证码错误";
            }
        }else{
            return "此手机没有发送验证码";
        }
    }
    //确认验证码
    function confirm_code(){
        $post = $this->input->post();
        if($post['tel'] && $post['code'] && $post['session_id']){
            $rs = $this->confirm_code_gerenal($post['tel'],$post['code']);
            if ($rs=="success"){
                    $data['status'] = "success";
                    $data['msg'] = "验证码正确";
                    $data['data'] = '';
            }else{
                $data['status'] = "fail";
                $data['msg'] = $rs;
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        echo json_encode($data);
    }

    //修改手机号
    function upd_tel(){
        $post = $this->input->post();
        if($post['id'] && $post['tel']){
            $usr = $this->db->where(array('tel'=>$post['tel']))->get("manager");
            if ($usr->result_array()){
                $data['status'] = "fail";
                $data['msg'] = "手机号已注册!";
                $data['data'] = '';
                echo json_encode($data);exit;
            }
            $data = $this->users_model->upd_user_info($post['id'],array('tel'=>$post['tel']));
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        echo json_encode($data);
    }


    //用户注册
    function register(){
        $post = $this->input->post();
        if($post['tel'] && $post['password'] && $post['code'] && $post['session_id']){
            $rs = $this->confirm_code_gerenal($post['tel'],$post['code']);
            if ($rs=="success"){
                $arr['tel']  = $post['tel'];
                $arr['password'] = $this->get_pwd($post['password']);
                $arr['identity'] = "试合作销售经理";
                $arr['created_at'] = date('Y-m-d H:i:s');
                $arr['entry_date'] = date('Y-m-d');
                // 唯一性校验 cj
                if(!check_one($this->db,'manager','tel',$post['tel']))
                {
                    $data['status'] = "fail";
                    $data['msg'] = "该手机号码已经注册";
                    $data['data'] = "";
                    json_send($data);exit;
                }
                $bool=$this->db->insert('manager',$arr);//将$data插入数据库的user表中
                $insert_id = $this->db->insert_id();
                if ($this->db->affected_rows()){
                    unset($_SESSION[$post['tel']."code"]);
                    $id = $this->db->insert_id();
                    //身份认证的时候添加一个信息
                    $this->db->insert('certification',array("manager_id"=>$id));
                    $data['status'] = "success";
                    $data['msg'] = "注册成功";
                    $data['data'] = $this->users_model->get_info($id);
                    $this->load->library('message', '', 'mylib');
                    $message_lib = $this->mylib;
                    $msg = "恭喜您".$arr['tel']."的机主注册成为文具1号的销售经理。";
                    // 绑定分享者为上级 cj
                    if($_POST['mid'])
                    {
                        $re = $this->wap_bind_up($insert_id,$_POST['mid']);
                        if($re['status'] == 'success')
                        {
                            $manager = $re['data'];
                            $msg .= "您的帐号已成功与大客户经理" . $manager['name'] . "（" . $manager['tel'] . "）绑定。如有疑问，详询4008215248。";
                        }else{
                            $msg .= "绑定失败，".$re['msg']."如有疑问，详询4008215248。";
                        }

                    }
                    // end
                    $bool_dx = $message_lib->send_msg($post['tel'],$msg,'','','',$needcheck=false);
                    if ($bool_dx['status'] != 'success'){
                        $data['msg'].=$bool_dx['msg'];
                    }

                    // 业绩表插入本月业绩
                    $insertdata = array(
                        'manager_id' => $id,
                        'performance' => 25000,
                        'recruit' => 0,
                        "completed_recruit"=>0,
                        "completed_performance"=>0,
                        "my_recruit"=>0,
                        "under_recruit"=>0,
                        "my_performance"=>0,
                        "under_performance"=>0,
                        'date' => date('Y-m',time())
                    );
                    $this->db->insert("norm",$insertdata);

                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "手机号已经存在";
                    $data['data'] = '';
                }
            }else{
                $data['status'] = "fail";
                $data['msg'] = $rs;
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
            if(!$post['tel'])
            {
                $data['msg'] = "请输入手机号";
            }
            if(!$post['password'])
            {
                $data['msg'] = "请输入密码";
            }
            if(!$post['code'])
            {
                $data['msg'] = "请输入验证码";
            }
            if(!$post['session_id'])
            {
                $data['msg'] = "验证码和手机号不匹配";
            }
        }
        echo json_encode($data);
    }

    //忘记密码
    function forget_pwd(){
        $post = $this->input->post();
        if($post['tel'] && $post['password'] && $post['code'] && $post['session_id']){
            $rs = $this->confirm_code_gerenal($post['tel'],$post['code']);
            if ($rs=="success"){
                $upd['tel'] = $post['tel'];
                $upd_data = array('password'=>$this->get_pwd($post['password']));
                $bool=$this->db->where($upd)->update('manager',$upd_data);//将$data插入数据库的user表中
                if ($bool){
                    unset($_SESSION[$post['tel']."code"]);
                    $data['status'] = "success";
                    $data['msg'] = "密码修改成功";
                    $data['data'] = '';
                }
            }else{
                $data['status'] = "fail";
                $data['msg'] = $rs;
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }


        echo json_encode($data);
    }

    //用户登录
    function login(){
        $post = $this->input->post();
        $post['registration_id'] = $post['registration_id']?$post['registration_id']:'无';
        if($post['tel'] && $post['password'] && $post['registration_id']){
            $usr = $this->db->where(array("tel"=>$post['tel'],'is_deleted'=>0))->get('manager')->result_array();
            if ($usr && count($usr)==1){

                if ($usr[0]['password'] == $this->get_pwd($post['password'])){
                    $this->db->where(array("tel"=>$post['tel']))->update("manager",array("registration_id"=>$post['registration_id']));
                    $data['status'] = "success";
                    $data['msg'] = "验证成功";
                    $data['data'] = $this->users_model->get_info($usr[0]['id']);
                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "密码错误";
                    $data['data'] ='';
                }
            } else{
                $data['status'] = "fail";
                $data['msg'] = "手机号不存在";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }


        echo json_encode($data);
    }

    //修改密码
    function upd_pwd(){
        $post = $this->input->post();
        if($post['id'] && $post['password'] && $post['new_password'] ){
            $usr = $this->db->where(array("id"=>$post['id']))->get('manager')->result_array();
            if ($usr && count($usr)==1){
                if ($usr[0]['password'] == $this->get_pwd($post['password'])){
                    $upd['id'] = $post['id'];
                    $upd_data = array('password'=> $this->get_pwd($post['new_password']));
                    $bool=$this->db->where($upd)->update('manager',$upd_data);
                    if ($bool){
                        $data['status'] = "success";
                        $data['msg'] = "修改成功";
                        $data['data'] ='';
                    }else{
                        $data['status'] = "fail";
                        $data['msg'] = "修改失败";
                        $data['data'] ='';
                    }
                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "密码错误";
                    $data['data'] ='';
                }
            } else{
                $data['status'] = "fail";
                $data['msg'] = "手机号不存在";
                $data['data'] = "";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }

        echo json_encode($data);
    }
//    //修改姓名
//    function upd_name(){
//        $post = $this->input->post();
//        if($post['id'] && $post['name']){
//            $data = $this->users_model->upd_user_info($post['id'],array('name'=>$post['name']));
//        }else{
//            $data['status'] = "fail";
//            $data['msg'] = "参数错误";
//            $data['data'] = "";
//        }
//        echo json_encode($data);
//    }
//    //修改姓别
//    function upd_gender(){
//        $post = $this->input->post();
//        if($post['id'] && $post['gender']){
//            $data = $this->users_model->upd_user_info($post['id'],array('gender'=>$post['gender']));
//        }else{
//            $data['status'] = "fail";
//            $data['msg'] = "参数错误";
//            $data['data'] = "";
//        }
//        echo json_encode($data);
//    }
//    //修改邮箱
//    function upd_email(){
//        $post = $this->input->post();
//        if($post['id'] && $post['email']){
//            $data =$this->users_model->upd_user_info($post['id'],array('email'=>$post['email']));
//        }else{
//            $data['status'] = "fail";
//            $data['msg'] = "参数错误";
//            $data['data'] = "";
//        }
//        echo json_encode($data);
//    }
//
//
//    //修改地址
//    function upd_address(){
//        $post = $this->input->post();
//        if($post['id'] && $post['province'] && $post['city'] && $post['district'] && $post['address']){
//            $arr = array(
//                'province'=>$post['province'],
//                'city'=>$post['city'],
//                'district'=>$post['district'],
//                'address'=>$post['address']
//            );
//            $data = $this->users_model->upd_user_info($post['id'],$arr);
//        }else{
//            $data['status'] = "fail";
//            $data['msg'] = "参数错误";
//            $data['data'] = "";
//        }
//        echo json_encode($data);
//    }


    function  upd_info(){

        $post = $this->input->post();
        $upd_data = json_decode($post['data'],true); //传过来的json字符转换为数组
        if ($post['id'] && $upd_data){
            //判断是否包含规定的几个键
            $exit = 0;
            $fileds = array("email","name","gender","province","city","district","address",'phone');
            foreach ($fileds as $v) {
                if (array_key_exists($v, $upd_data)) {
                    $exit = 1;
                }
            }
            if($post['id'] && $exit){
                $arr = $upd_data;
                $data = $this->users_model->upd_user_info($post['id'],$arr);
            }else{
                $data['status'] = "fail";
                $data['msg'] = "参数错误";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
       json_send($data);
    }




    function new_pic(){
       $post = $this->input->post();
        if($post['id'] && $_FILES['pic']['name']){
            $this->load->library('FileUpload','','mylib');
            $up = $this->mylib;
//            echo $this->config->item("upload_path");exit;
            $up->set("path",$this->config->item("upload_path"));
            $up->set("maxsize",2000000); //kb
            $up->set("allowtype",array("gif","png","jpg","jpeg"));//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件，注意设置其文件大小
            $up->set("israndname",true);//true:由系统命名；false：保留原文件名

            //使用对象中的upload方法，上传文件，方法需要传一个上传表单的名字name：pic
            //如果成功返回true，失败返回false

            if($up->upload("pic")){
                $upd['id'] = $post['id'];
                $path = $up->getFileName();
                $bool=$this->db->where($upd)->update('manager',array("pic_path"=>$path));
                if ($bool){
                    $data['status'] = "success";
                    $data['msg'] = "上传成功";
                    $data['data'] = $this->config->item("upload_url").$path;
                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "上传失败";
                    $data['data'] = "";
                }

            }else{
                $data['status'] = "fail";
                $data['msg'] = "上传失败". $up->getErrorMsg().'路径是：'.$up->getPath();
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }

        echo json_encode($data);

    }




    //获取个人信息
    function info(){
        if($_GET['id']){
            $info = $this->users_model->get_info($_GET['id']);
            if ($info){
                $info = changecontent($info);
                $data['status'] = "success";
                $data['msg'] = "获取成功";
                $data['data'] = $info;
            }else{
                $data['status'] = "fail";
                $data['msg'] = "用户不存在";
                $data['data'] = "";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        echo json_encode($data);
    }

    //意见反馈
    function opinion(){
        $post = $this->input->post();
        if($post['content'] && $post['id']){
            $arr['manager_id'] = $post['id'];
            $arr['content'] = $post['content'];
            $arr['created_at'] = date("Y-m-d H:i:s");
            $bool=$this->db->insert('opinion',$arr);
            if ($this->db->affected_rows()) {
                $insert_id = $this->db->insert_id();
                $data['status'] = "success";
                $data['msg'] = "提交成功";
                $data['data'] = "";
                if ($_FILES['pic']['name']){
                    $this->load->library('FileUpload','','mylib');
                    $up = $this->mylib;
                    $up->set("path",$this->config->item("upload_path"));
                    $up->set("maxsize",2000000); //kb
                    $up->set("allowtype",array("gif","png","jpg","jpeg"));//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件，注意设置其文件大小
                    $up->set("israndname",true);//true:由系统命名；false：保留原文件名
                    if($up->upload("pic")){
                        $upd['id'] = $post['id'];
                        foreach ($up->getFileName() as  $v){
                            $path = $v;
                            $bool=$this->db->insert('opinion_pic',array("pic_path"=>$path,'opinion_id'=>$insert_id));
                        }
                    }else {
                        $data['msg'] = implode(",",$up->getErrorMsg());

                        $data['data'] = "";
                    }
                }
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }
    // wap分享注册绑定上级
    function wap_bind_up($nid,$uid){
        // 上级经理信息
        $manager = $this->db->where(array('id'=>$uid))->get("manager")->row(0,'array');
        // 当前注册人信息
//        $manager_register = $this->db->where(array('id'=>$nid))->get("manager")->row(0,'array');
        if ($manager){
            if($manager['manager_status']!="已离职"){

                $bool_bind = $this->users_model->bind($nid, $uid,"","");
                if ($bool_bind['status']=="success") {
                    $data['status'] = "success";
                    $data['msg'] = "绑定成功";
                    $data['data'] = $manager;
//                    //发送短信
//                    $msg = "【文具1号】亲爱的" . $manager_register['name'] . "，您的帐号已成功与大客户经理" . $manager['name'] . "（" . $manager['tel'] . "）绑定。如有疑问，详询4008215248。";
//                    // 重写发短信
//                    $this->load->library('message', '', 'mylib');
//                    $message_lib = $this->mylib;
//                    // end
//                    $bool_dx = $message_lib->send_msg($manager_register['tel'], $msg);
//                    if ($bool_dx['status'] != 'success') {
//                        $data['msg'] .= "，".$bool_dx['msg'];
//                    }
                } else{
                    $data['status'] = "fail";
                    $data['msg'] = "绑定失败";
                    $data['data'] = "";
                }
            }else{
                $data['status'] = "fail";
                $data['msg'] = "该大客户经理已离职";
                $data['data'] = "";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "无此大客户经理";
            $data['data'] = "";
        }
        return $data;
    }
    //绑定大客户经理
    function bind_manager(){
        $post = $this->input->post();
        if ($post['id'] && $post['tel'] && $post['name']){
            //销售经理信息
            $usr = $this->db->where(array("id"=>$post['id']))->get("manager")->row_array();
            if ($usr['is_bind']=="已绑定"){
                $data['status'] = "fail";
                $data['msg'] = "已在绑定中";
                $data['data'] = "";
                json_send($data);exit;
            }
            $result = $post['result'];
            $map['tel'] = $post['tel'];
            $map['name'] = $post['name'];
//            $map['identity'] = "大客户经理";
            $identify_arr = array("大客户经理","销售经理","城市经理",'大客户经理','资深大客户经理','特聘大客户经理','合作销售经理','试合作销售经理');
            $map['is_deleted'] =0;
            //大客户经理信息
            $manager = $this->db->where($map)->get("manager")->result_array();
            if ($manager && in_array($manager[0]['identity'],$identify_arr)){
                if($manager[0]['manager_status']!="已离职"){

                    $bool_bind = $this->users_model->bind($post['id'], $manager[0]['id'],"","");
                        if ($bool_bind['status']=="success") {
                            $data['status'] = "success";
                            $data['msg'] = "绑定成功";
                            $data['data'] = "";
                            //发送短信
                            $msg = "【文具1号】亲爱的" . $usr['name'] . "，您的帐号已成功与" . $manager[0]['identity'] . $manager[0]['name'] . "（" . $manager[0]['tel'] . "）绑定。";
                            // 查询上级
//                            if($manager[0]['identity'] == '合作销售经理' || $manager[0]['identity'] == '试合作销售经理')
//                            {
//                                $prent_id = $this->db->where(array('manager_id'=>$manager[0]['id']))->get("manager_bind")->result_array();
//                                if($prent_id)
//                                {
//                                    $parent_info = $this->db->where(array('id'=>$prent_id[0]['parent_id']))->get("manager")->result_array();
//                                    if($parent_info)
//                                    {
//                                        $msg .= "默认归属" . $parent_info[0]['identity'] . $parent_info[0]['name'] . '。';
//                                    }
//                                }
//                            }
                            $msg .= "如有疑问，详询4008215248。";
                            // 重写发短信
                            $this->load->library('message', '', 'mylib');
                            $message_lib = $this->mylib;
                            // end
                            $bool_dx = $message_lib->send_msg($usr['tel'], $msg);
                            if ($bool_dx['status'] != 'success') {
                                $data['msg'] .= "，".$bool_dx['msg'];
                            }
                        } else{
                            $data['status'] = "fail";
                            $data['msg'] = $bool_bind['msg'] ? $bool_bind['msg'] : '绑定失败';
                            $data['data'] = "";
                        }
                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "该大客户经理已离职";
                    $data['data'] = "";
                }

            }else{
                $data['status'] = "fail";
                $data['msg'] = "无此经理";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }
    // 获取上级信息和绑定状态 cj
    function get_parent_sinfo(){
        if($_GET['id'])
        {
            $mb_info = $this->db->where(["manager_id"=>$_GET['id']])->get("manager_bind")->row_array();
            $id_info = $this->db->where(["id"=>$_GET['id']])->get("manager")->row_array();
            // 如果是大区经理 那么直接是绑定总监的
            if(preg_match('/大区经理/',$id_info['identity']))
            {
                $binfo = $this->get_boss_info();
                if($binfo)
                {
                    $btime = $this->db->where(["parent_id"=>$binfo['id'],"manager_id"=>$_GET['id']])->get("manager_bind")->row_array()['bind_time'];
                    $res['parent_id'] = $binfo['id'];
                    $res['pic_path'] = $binfo['pic_path']?$this->config->item("upload_url").$binfo['pic_path']:"";
                    $res['name'] = $binfo['name'];
                    $res['phone'] = $binfo['phone'];
                    $res['tel'] = $binfo['tel'];
                    $res['bind_time'] = $btime;
                    $data['status'] = "success";
                    $data['msg'] = "请求成功";
                    $data['data'] = $res;
                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "数据错误";
                    $data['data'] = "";
                }
                json_send($data);
                return;
            }
            if($mb_info)
            {
                $parent_id = $mb_info['parent_id'];
                $bind_time = $mb_info['bind_time'];
                $manager_info = $this->db->where(["id"=>$parent_id])->get("manager")->row_array();
                // 绑定审核状态
                $status_arr = array('申请绑定中','绑定成功','绑定失败','申请解绑中','解绑成功','解绑失败');
                $sql = "SELECT
                    manager_id,
                    parent_id,
                    `status`
                FROM
                    manager_bind_status
                WHERE
                    parent_id = ".$parent_id." 
                AND manager_id = ".$_GET['id'] .
                    " ORDER BY created_at DESC limit 1";
                $rs = $this->db->query($sql)->row_array();
                if($rs['status'] == $status_arr[3])
                {
                    $res['unbind_status'] = '解绑审核中';
                }else{
                    $res['unbind_status'] = '解绑';
                    // 新增，如果绑定对象是销售经理，查询是否有上级
                    // 查询上级
                    if(preg_match('/销售经理/',$manager_info['identity']))
                    {
                        $qr = $this->users_model->get_one_father_id($manager_info['id'],'大客户经理');
                            if($qr)
                            {
                                $parent_info = $this->db->where(array('id'=>$qr))->get("manager")->row_array();
                                $pinfo['id'] = $parent_info['id'];
                                $pinfo['pic_path'] = $manager_info['pic_path']?$this->config->item("upload_url").$manager_info['pic_path']:"";
                                $pinfo['name'] = $parent_info['name'];
                                $pinfo['phone'] = $parent_info['phone'];
                                $pinfo['tel'] = $parent_info['tel'];
                                $pinfo['identity'] = $parent_info['identity'];
                                $res['city_manager_info'] = $pinfo;
                            }
                    }
                }

                $res['parent_id'] = $manager_info['id'];
                $res['pic_path'] = $manager_info['pic_path']?$this->config->item("upload_url").$manager_info['pic_path']:"";
                $res['name'] = $manager_info['name'];
                $res['phone'] = $manager_info['phone'];
                $res['tel'] = $manager_info['tel'];
                $res['identity'] = $manager_info['identity'];
                $res['bind_time'] = $bind_time;
                $data['status'] = "success";
                $data['msg'] = "请求成功";
                $data['data'] = $res;
            }else{
                $data['status'] = "fail";
                $data['msg'] = "尚未绑定";
                $data['data'] = "";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 获取总监信息 cj
    function get_boss_info(){
//       $bos_info = $this->db->get("key_value")->result_array();
//       if($bos_info)
//       {
//           foreach ($bos_info as $binfo)
//           {
//                $res[$binfo['key']] = $binfo['value'];
//           }
//           return $res;
//       }
        $sql = "select * from manager WHERE identity = '销售总监'";
        $rs = $this->db->query($sql)->row_array();
        if($rs){
            return $rs;
        }
       return false;
    }

    //解绑大客户经理 cj
    function cancel_bind_manager(){
        $post = $this->input->post();
        if ($post['id'] && $post['parent_id']){
            $map['manager_id'] = $post['id'];
            $map['parent_id'] = $post['parent_id'];
            $this->cancel_bind_manager_check($map);
            // 插入审核表
            $insertdata['manager_id'] = $post['id'];
            $insertdata['parent_id'] = $post['parent_id'];
            $insertdata['status'] = '申请解绑中';
            $insertdata['created_at'] = date("Y-m-d H:i:s");

            $bool = $this->db->insert("manager_bind_status",$insertdata);
            if ($bool){
//                $this->db->where(array("id"=>$post['id']))->update("manager",array("is_bind"=>"未绑定"));
                $data['status'] = "success";
                $data['msg'] = "申请解绑成功";
                $data['data'] = "";
            }else{
                $data['status'] = "fail";
                $data['msg'] = "申请解绑失败";
                $data['data'] = "";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 校验是否能解绑
    private function cancel_bind_manager_check($data)
    {
        $manager_id = $data['manager_id'];
        $parent_id = $data['parent_id'];

        $re = $this->db->where(["manager_id"=>$manager_id,'parent_id'=>$parent_id])->get("manager_bind")->row_array();
        if(!$re)
        {
            $res['status'] = "fail";
            $res['msg'] = "没有绑定关系!";
            $res['data'] = '';
            json_send($res);
            exit();
        }
        $status_arr = array('申请绑定中','绑定成功','绑定失败','申请解绑中','解绑成功','解绑失败');
        $sql = "SELECT
                    manager_id,
                    parent_id,
                    `status`
                FROM
                    manager_bind_status
                WHERE
                    parent_id = ".$parent_id." 
                AND manager_id = ".$manager_id .
            " AND `status` IN ('".$status_arr[3]."') ORDER BY created_at DESC limit 1";

        $rs = $this->db->query($sql)->result_array();
        if($rs)
        {
            $rs = $rs[0];
            if($rs['status'] == $status_arr[3])
            {
                $res['status'] = "fail";
                $res['msg'] = "申请解绑中,请勿重复申请!";
                $res['data'] = '';
                json_send($res);
                exit();
            }
            if($rs['status'] == $status_arr[4])
            {
                $res['status'] = "fail";
                $res['msg'] = "解绑成功,请勿重复申请!";
                $res['data'] = '';
                json_send($res);
                exit();
            }
        }


    }

    // 实名认证 企业
    function identify_company(){
        $post = $this->input->post();
        if(isset($post['account_type']) && $post['account_type'] == '银行卡')
        {
            $post['account_type'] = '银行卡';
        }else{
            $post['account_type'] = '支付宝';
        }
        if ($id = $post['id']){
//            if(!$post['alipay_name'] || !$post['alipay_account']){
//                $data['status'] = "fail";
//                $data['msg'] = "支付宝账号和姓名必填!";
//                $data['data'] = '';
//                echo json_encode($data);exit;
//            }
            $manager = $this->db->where(array("manager_id"=>$id))->get("company")->row_array();
            if ($manager){
                unset($post['id']);
                unset($post['submit']);
                $bool1 = $this->db->where(["manager_id"=>$id])->update("company",$post);
            }else{
                $post['manager_id'] = $id;
                unset($post['id']);
                unset($post['submit']);
                $bool1 = $this->db->insert("company",$post);
            }

        }

        if($_FILES['pic']['name']){
//                log_message("error",json_encode($_FILES));
            $this->load->library('FileUpload','','mylib');
            $up = $this->mylib;
            $up->set("path",$this->config->item("upload_path"));
            $up->set("maxsize",2000000); //kb
            $up->set("allowtype",array("gif","png","jpg","jpeg"));//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件，注意设置其文件大小
            $up->set("israndname",true);//true:由系统命名；false：保留原文件名
            if($up->upload("pic")){
                $upd['id'] = $post['id'];
                $upd_data['pic_path'] = $up->getFileName();
            }else{
                $up_msg=",图片上传失败";
            }

            if($upd_data){
                $bool2 = $this->db->where(["manager_id"=>$id])->update("company",$upd_data);
            }

        }
        if($bool1 || $bool2){
            $this->db->where(["id"=>$id])->update("manager",array('certification_status'=>'已提交','certification_type'=>'企业'));
            $data = array(
                "status"=>"success",
                "msg"=>"上传成功",
                "data"=>""
            );
        }else{

            $data = array(
                "status"=>"fail",
                "msg"=>"上传失败",
                "data"=>""
            );
        }
        if($up_msg){
            $data['msg'].=$up_msg;
        }
        json_send($data);
    }

    //实名认证
    function identify(){
        $post = $this->input->post();
        if(isset($post['account_type']) && $post['account_type'] == '银行卡')
        {
            $post['account_type'] = '银行卡';
        }else{
            $post['account_type'] = '支付宝';
        }
        if ($id = $post['id']){
            if($tel= $post["bankcard_phone"]){
                if (!is_mobile($tel)){
                    $data['status'] = "fail";
                    $data['msg'] = "手机号格式错误!";
                    $data['data'] = '';
                    echo json_encode($data);exit;
                }
            }
            if(!$post['alipay_name'] || !$post['alipay_account']){
                $data['status'] = "fail";
                $data['msg'] = "支付宝账号和姓名必填!";
                $data['data'] = '';
                echo json_encode($data);exit;
            }
             $manager = $this->db->where(array("manager_id"=>$id))->get("certification")->row_array();
            if ($manager){
                unset($post['id']);
                unset($post['submit']);
                $bool1 = $this->db->where(["manager_id"=>$id])->update("certification",$post);
            }else{
                $post['manager_id'] = $id;
                unset($post['id']);
                unset($post['submit']);
                $bool1 = $this->db->insert("certification",$post);
            }

        }

            if($_FILES['front_pic']['name'] || $_FILES['back_pic']['name']){
//                log_message("error",json_encode($_FILES));
                $this->load->library('FileUpload','','mylib');
                $up = $this->mylib;
                $up->set("path",$this->config->item("upload_path"));
                $up->set("maxsize",2000000); //kb
                $up->set("allowtype",array("gif","png","jpg","jpeg"));//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件，注意设置其文件大小
                $up->set("israndname",true);//true:由系统命名；false：保留原文件名
                if($up->upload("front_pic")){
                    $upd['id'] = $post['id'];
                    $upd_data['front_pic_path'] = $up->getFileName();
                }else{
                     $up_msg=",正面照上传失败";
                }

                    if($up->upload("back_pic")){
                        $upd_data['back_pic_path']= $up->getFileName();
                    }else{
                        $up_msg1=",背面照上传失败";
                    }
                if($upd_data){
                    $bool2 = $this->db->where(["manager_id"=>$id])->update("certification",$upd_data);
                }

            }
        if($bool1 || $bool2){
            $this->db->where(["id"=>$id])->update("manager",array('certification_status'=>'已提交','certification_type'=>'个人'));
                $data = array(
                    "status"=>"success",
                    "msg"=>"上传成功",
                    "data"=>""
                );
        }else{

            $data = array(
                "status"=>"fail",
                "msg"=>"上传失败",
                "data"=>""
            );
        }
        if($up_msg){
            $data['msg'].=$up_msg;
        }
        if($up_msg1){
            $data['msg'].=$up_msg1;
        }
        json_send($data);
    }

    //实名认证信息
    function identity_info(){
        if ($_GET['id'] && $_GET['type']){
            $id = $_GET['id'];
            $type = $_GET['type'];
            if($type == 1)
            {
                // 个人认证
                $info = $this->db->where(["manager_id"=>$id])->get("certification")->result_array();
                if ($info){
                    $info[0]['front_pic_path'] =  $info[0]['front_pic_path']?$this->config->item("upload_url").$info[0]['front_pic_path']:"";
                    $info[0]['back_pic_path'] =  $info[0]['back_pic_path']?$this->config->item("upload_url").$info[0]['back_pic_path']:"";
                    $data['data'] = $info[0];
                }else{
                    $data['data'] = "";
                }
            }else{
                // 企业认证
                $info = $this->db->where(["manager_id"=>$id])->get("company")->result_array();
                if ($info){
                    $info[0]['pic_path'] =  $info[0]['pic_path']?$this->config->item("upload_url").$info[0]['pic_path']:"";
                    $data['data'] = $info[0];
                }else{
                    $data['data'] = "";
                }
            }

            $data['status'] = "success";
            $data['msg'] = "获取成功";

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);

    }
    //消息通知
    function message(){
        if($_GET['id']){
            $id = $_GET['id'];
            $sql = "select * from message where manager_id=$id and is_deleted = 0 order by id desc";
            $page = $_GET['page']?$_GET['page']:1;
            $limit= $_GET['limit']?$_GET['limit']:10;
            $limit_from = ($page-1)*$limit;
            $sql.=" limit ".$limit_from.",".$limit;
            $rs = $this->db->query($sql)->result_array();

            //进消息列表，把所有改成已读

//            var_dump($rs);
//            eixt;
//            if($rs){
//                foreach ($rs as &$v){
//                    $v['read'] = $v['read']?"已读":"未读";
//                }
//            }
            $data['data'] = $rs;
            $data['status'] = "success";
            $data['msg'] = "获取成功";
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }
    //消息通知
    function message_count(){
        if($_GET['id']){
            $id = $_GET['id'];
            $data['data'] = $this->users_model->get_message_count($id);
            $data['status'] = "success";
            $data['msg'] = "获取成功";
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }
    //未读消息数清0
    function message_clear(){
        if($_GET['id']){
            $id = $_GET['id'];
            $this->db->where(array("manager_id"=>$id))->update("message",array("have_read"=>1));
            $data['data'] = "";
            $data['status'] = "success";
            $data['msg'] = "成功";
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 删除一条或者所有消息 cj
    function message_delete(){
        $post = $this->input->post();
        if($post['cid'] && $post['id'])
        {
            $id = $post['id'];
            $cid = $post['cid'];
            if($post['id'] == 'all')
            {
                $bool = $this->db->where(array("manager_id"=>$cid))->update("message",array("is_deleted"=>1));
            }else{
                $bool = $this->db->where(array("id"=>$id,"manager_id"=>$cid))->update("message",array("is_deleted"=>1));
            }
            if($bool)
            {
                $data['data'] = "";
                $data['status'] = "success";
                $data['msg'] = "成功";
            }else{
                $data['status'] = "fail";
                $data['msg'] = "删除失败";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }


   function  get_areas(){
        $areas = $this->areas->get_areas();
        $data['msg'] = "获取成功";
        $data['status'] = "success";
        $data['data'] = $areas;
        json_send($data);
   }


   function  get_pwd($pwd = ""){
       $md5_str = $this->config->item("md5_str");
       return md5_encrypt($pwd,$md5_str);

   }


//
//    public function send_msg($uid, $msg, $pid = 0) {
//        $this->set_table_data('message', array('title' => $msg, 'uid' => $uid, 'pid' => $pid));
//        $user = $this->get_table_data('user', array('id' => $uid), FALSE);
//        if ($user && count($user) && $user['registration_id']) {
//            $this->push_message($user['registration_id'], $msg);
//            return TRUE;
//        } else {
//            return FALSE;
//        }
//    }

    public function push_message($register_id, $msg) {
//        $this->load->library('Jpush','','mylib');
//        $jpush = $this->mylib;
//        $jpush->push($receiver=array('registration_id'=>array('123123')),$title='111','neirong',$extras=array(),$m_time = '86400');
//
        $this->load->library('Jpush', '', 'mylib');
        $jpush = $this->mylib;
        $rr = $jpush->push($receiver = array('registration_id' => array('100d8559097d480c09b')), $title = 'test测试', '测试内容', $extras = array(), $m_time = '86400');
        print_r($rr);

        //组装需要的参数
        //$receive = 'all';     //全部
        //$receive = array('tag'=>array('1','2','3'));      //标签
        //$receive = array('alias'=>array('111'));    //别名
        $receive = array('registration_id' => array($register_id));
        $title = '行早股权通知';
        $content = $msg;
        $m_time = '86400';        //离线保留时间
        $extras = array("versionname" => '1', "versioncode" => '2');   //自定义数组
        //调用推送,并处理
        $result = $pushObj->push($receive, $title, $content, $extras, $m_time);
        if ($result) {
            $res_arr = json_decode($result, true);
            if (isset($res_arr['error'])) {   //如果返回了error则证明失败
                //错误信息 错误码
                log_message('error', $res_arr['error']['message'] . '：' . $res_arr['error']['code']);
            } else {
                //处理成功的推送......
                //可执行一系列对应操作~
                log_message('info', '推送成功~');
            }
        } else {      //接口调用失败或无响应
            log_message('error', '接口调用失败或无响应~');
        }
    }


    //添加销售经理下一步
    function confirm_tel(){
       $post = $this->input->post();
       if ($post['id'] && $post['tel']){
            //根据手机号得到信息
            $info = $this->users_model->get_one_by_tel($post['tel']);
//            var_dump($info);exit;
            if ($info){
                if(!preg_match("/销售经理/",$info["identity"])){
                    $data['msg'] = "此用户已存在，不是销售经理";
                    $data['code'] = 1;
                    $data['status'] = "fail";
                    $data['data'] = "";
                    json_send($data);
                    exit;
                }
                    if ($info['is_bind']=="已绑定"){
                        $data['msg'] = "该销售经理已经绑定,请勿重复绑定!";
                        $data['code'] = 2;
                        $data['status'] = "fail";
                        $data['data'] = "";
                        json_send($data);
                        exit;
                    }else{
                        $data['msg'] = "该销售经理未被绑定,可以绑定!";
                        $data['code'] = 3;
                        $data['status'] = "success";
                        $data['data'] = $info['id'];
                    }
                }else{
                    $data['msg'] = "该手机未被注册,可以绑定!";
                    $data['code'] = 4;
                    $data['status'] = "success";
                    $data['data'] = "";
                }
        }else{
           $data['msg'] = "参数错误!";
           $data['code'] = 0;
           $data['status'] = "fail";
           $data['data'] = "";
       }
      json_send($data);
    }

    //添加销售经理
    function add_manager(){
        $post = $this->input->post();
        if ($post['id'] && $post['name'] && $post['tel']){

                if(!check_name($post['name'])){
                    $data['status'] = "fail";
                    $data['msg'] = "姓名必须是中文和字母,不能超过10位!";
                    $data['data'] = "";
                     json_send($data);exit;
                }
                // 校验手机号码唯一性 cj
                if(!check_one($this->db,'manager','tel',$post['tel']))
                {
                    $data['status'] = "fail";
                    $data['msg'] = "该手机号码已经注册";
                    $data['data'] = "";
                    json_send($data);exit;
                }
            $reason = $post['reason'];
            $record = $post['record'];
            //销售经理信息
            $usr = $this->users_model->get_one_by_tel($post['tel']);
            //大客户经理信息
            $usr1 = $this->users_model->get_one($post['id']);
            if ($usr){
                $bool_bind = $this->users_model->bind($usr['id'],$post['id'],"申请绑定中",$reason,$check_status=true);
                // 可以绑定性校验 cj
                if($bool_bind['status']!="success")
                {
                    $data['msg'] = $bool_bind['msg'];
                    $data['status'] = "fail";
                    $data['data'] = "";
                    json_send($data);
                    exit();
                }
                if ($bool_bind['status']=="success"){
                    if ($record){
                        $record_data = array(
                            "manager_id"=>$usr['id'],
                            "parent_id"=>$post['id'],
                            "content"=>$record,
                            "created_at"=>date("Y-m-d h:is")
                         );
                        $this->db->insert("manager_record",$record_data);
                    }

                    $data['msg'] = "申请成功";
                    $data['status'] = "success";
                    $data['data'] = "";
                }else{
                    $data['msg'] = "申请失败";
                    $data['status'] = "fail";
                    $data['data'] = "";
                }
            }else{
                // 所有通过申请或添加的销售经理都以试合作销售经理开始;
                $add_data = array("name"=>$post['name'],"tel"=>$post['tel'],"identity"=>"试合作销售经理","created_at"=>date("Y-m-d H:i:s"));
                $add_data['password'] = $this->get_pwd(substr($post['tel'],-6));
                $add_data['email'] = $post['email']?$post['email']:"";
                $add_data['gender'] = $post['gender']?$post['gender']:"";
                $add_data['phone'] = $post['phone']?$post['phone']:"";
                $rs = $this->users_model->validate($add_data);
                if($rs['status']=="fail"){
                    json_send($rs);exit;
                }
                $bool = $this->db->insert("manager",$add_data);
                if ($this->db->affected_rows()){
                    $insert_id = $this->db->insert_id();
                    //添加绑定信息
                    $bool_bind = $this->users_model->bind($insert_id,$post['id'],"",$reason);
                    if($bool_bind['status']!="success")
                    {
                        $data['msg'] = $bool_bind['msg'];
                        $data['status'] = "fail";
                        $data['data'] = "";
                        json_send($data);
                        exit();
                    }
                    if ($record){
                        $record_data = array(
                            "manager_id"=>$insert_id,
                            "parent_id"=>$usr1['id'],
                            "content"=>$record,
                            "created_at"=>date("Y-m-d h:is")
                        );
                        $this->db->insert("manager_record",$record_data);
                    }
                    //身份认证的时候添加一个信息
                    $this->db->insert('certification',array("manager_id"=>$insert_id));
                    $msg = "【文具1号】恭喜您注册成为销售经理！您的帐号：".$add_data['tel']."，密码：手机号后6位，请及时下载APP登录并修改密码。下载地址t.cn/RLEuUyh";
                    $data['status'] = "success";
                    $data['msg'] = "添加成功";
                    $data['data'] = "";
                    // 重写发短信
                    $this->load->library('message', '', 'mylib');
                    $message_lib = $this->mylib;
                    // end
                    $bool_dx = $message_lib->send_msg($post['tel'],$msg);
                    if ($bool_dx['status'] != 'success'){
                        $data['msg'].="，".$bool_dx['msg'];;
                    }
                }else{
                    $data['msg'] = "添加失败";
                    $data['status'] = "fail";
                    $data['data'] = "";
                }
            }
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    //数据统计(销售经理)
    function  data_count(){
        $data = $this->users_model->data_count($_GET['id'],$_GET['year'],$_GET['month']);
        json_send($data);

    }

    //数据统计2大客户经理
    function data_count_ciy(){
        $data = $this->users_model->data_count_ciy($_GET['id'],$_GET['year'],$_GET['month']);
        json_send($data);
    }


    //数据统计3大区经理
    function data_count_district(){
        $data = $this->users_model->data_count_district($_GET['id'],$_GET['year'],$_GET['month']);
        json_send($data);
    }
    //业绩指标(大客户经理,大区，经理) cj
    function city_performance(){
        if($id = $_GET['id']){
            $usr = $this->users_model->get_one($_GET['id']);
            if(!$usr){
                $data['msg'] = "无此经理";
                $data['status'] = "fail";
                $data['data'] = "";
                json_send($data);exit;
            }
            $arr['created_at'] = date("Y-m-d",strtotime($usr['created_at']));
            //计算加入天数
            $d1 = strtotime(date("Y-m-d",strtotime($arr['created_at'])));
            $d2 = strtotime(date("Y-m-d"));
            $days = round(($d2-$d1)/3600/24);
            $arr['days'] = $days == 0 ? 1 : $days;
            //本月指标和完成的信息
            $curent = $this->users_model->get_norm($_GET['id']);
            // 团队本月业绩合计
            $curent['curent_team'] = $curent['completed_performance'] - $curent['my_performance'];
            // 上月总业绩
            $last_month_sum = $this->users_model->get_last_month_sum($_GET['id']);
            //下个月的
            $time = getNextMonthDays(date("Y-m-d"));
            $month = date("Y-m",strtotime($time[0]));
            $next = $this->users_model->get_norm($_GET['id'],$month);
            // 累计个人完成业绩
            $sum_performance = $this->users_model->get_norm_sum($_GET['id']);
            // 累计团队完成业绩
            $sum_performance['sum_team_performance'] = $sum_performance['completed_performance_sum'] - $sum_performance['my_performance_sum'];
            //当前如果没有
            if (!$curent){
                $curent['performance']= 0;
                $curent['recruit'] = 0;
                $curent['completed_performance']= 0;
                $curent['orders']= 0;
                $curent['completed_recruit']= 0;
                $curent['date'] = date("Y-m");
            }
            if (!$next){
                $performance = month_norm($this->db,$_GET['id']);
                $next['performance']= $performance;
                $next['recruit'] = 0;
                $next['completed_performance']= 0;
                $next['orders']= 0;
                $next['completed_recruit']= 0;
                $next['date'] = date("Y-m",strtotime("+ 1 month"));
            }

            if (preg_match('/大区经理/',$usr['identity'])){
                $sql = "SELECT group_concat(manager_id) mg_ids,count(manager_id) mg_count from manager_bind mb  where mb.parent_id=$id ";
                $mg = $this->db->query($sql)->row_array();
                if(!$mg['mg_count']){
                    $next['can_distribute'] = 0;
                }else{
                    //查看下个月的下级是否都已分配指标
                    $sql = "select ifnull(sum(performance),0) per_sum,ifnull(sum(recruit),0) re_sum from norm where manager_id in (select manager_id from manager_bind where parent_id = $id ) and date='".$month."'";

                    $row = $this->db->query($sql)->row_array();

                    if ($next['performance']){
                        if ( ($next['performance']>$row['per_sum']) || $next['recruit']>$row['re_sum'] ){
                            $next['can_distribute'] = 1;
                        }else{
                            $next['can_distribute'] = 0;
                        }
                    }else{
                        $next['can_distribute'] = 0;
                    }
                }
            }

            // 达标人数
            if(preg_match('/销售经理/',$usr['identity']))
            {
                $arr['standard_count'] = 7;
            }elseif(preg_match('/特聘大客户经理/',$usr['identity'])){
                $arr['standard_count'] = 20;
            }elseif(preg_match('/大客户经理/',$usr['identity'])){
                $arr['standard_count'] = 20;
            }elseif(preg_match('/资深大客户经理/',$usr['identity'])){
                $arr['standard_count'] = 20;
            }elseif(preg_match('/大区/',$usr['identity'])){
                $arr['standard_count'] = 30;
            }
            $arr['curent'] = $curent;
            $arr['last_month_sum'] = $last_month_sum;
            $arr['next'] = $next;
            $arr['sum_performance'] =$sum_performance;
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;

        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }
    //业绩指标(大区经理)
    function district_performance(){
        if($id = $_GET['id']){
            $usr = $this->users_model->get_one($_GET['id']);
            $arr['created_at'] = $usr['created_at'];
            //计算加入天数
            $d1 = strtotime(date("Y-m-d",strtotime($arr['created_at'])));
            $d2 = strtotime(date("Y-m-d"));
            $days = round(($d2-$d1)/3600/24);
            $arr['days'] = $days;
            //本月指标信息
            $curent = $this->users_model->get_norm($_GET['id']);
            //当月订单总数
            $date_str = date("Y-m");
            //下个月的
            $time = getNextMonthDays(date("Y-m-d"));
            $month = date("Y-m",strtotime($time[0]));
            $next = $this->users_model->get_norm($_GET['id'],$month);

            $sum = $this->users_model->get_norm_sum($_GET['id']);
            //当前如果没有
            if (!$curent){
                $curent['performance']= "无";
                $curent['recruit'] = "无";
                $curent['completed_performance']= 0;
                $curent['orders']= 0;
                $curent['completed_recruit']= 0;
                $curent['date'] = date("Y-m");
            }
            if (!$next){
                $next['performance']= "无";
                $next['recruit'] = "无";
                $next['completed_performance']= 0;
                $next['completed_recruit']= 0;
                $next['orders']= 0;
                $next['date'] = date("Y-m",strtotime("+ 1 month"));
            }
            $arr['curent'] = $curent;
            $arr['next'] = $next;
            $arr['sum'] =$sum;
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;

        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }
    //平均分配指标到下级
    function equal_distribute(){
        $data = $this->users_model->equal_distribute($_GET['id']);
        json_send($data);
    }
    //业绩历史指标(大客户经理，销售经理，大区)
    function city_performance_list(){
        if ($_GET['id']){
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:3;

            $arr =  $this->users_model->norm_list($_GET['id'],$_GET['start'],$_GET['end'],$page,$limit);
            // 增长指标
            $usr = $this->users_model->get_one($_GET['id']);
            if(preg_match('/销售经理/',$usr['identity']))
            {
                $data['standard_count'] = 1;
            }elseif(preg_match('/大客户/',$usr['identity'])){
                $data['standard_count'] = 1;
            }elseif(preg_match('/大区/',$usr['identity'])){
                $data['standard_count'] = 0.2;
            }
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 申请晋升 cj
    function apply_upgrade(){
        if($_GET['id'])
        {
            // 身份查询
            $m_info = $this->users_model->get_one($_GET['id']);
            if($m_info)
            {
                $res = check_upgrade($this->db,$_GET['id']);
                if($res)
                {
                    if($res['res'] == 1)
                    {
                        // 可以晋升
                        $now_identity = $m_info['identity'];
                        $next_identity = next_identity($m_info['identity'])[0];
                        // 如果有父级，存入奖金 push_money
                        if($m_info['is_bind'] == '已绑定')
                        {
                            $sql = "SELECT parent_id FROM manager_bind WHERE manager_id = ".$_GET['id']." limit 1";
                            $parent_id = $this->db->query($sql)->row_array()['parent_id'];
                            $push_money = next_identity($m_info['identity'])[1];
                        }
                        $message = $this->users_model->add_upgrade($_GET['id'],$parent_id,$push_money,$now_identity,$next_identity);
                    }else{
                        // 不可以晋升
                        $message = '不满足条件，无法晋升';
                    }
                    $data['data']['res'] = $res['res'];
                    $data['data']['message'] = $message;
                    $data['status'] = "success";
                    $data['msg'] = "获取成功";
                }else{
                    $data['msg'] = "数据错误，请联系管理方";
                    $data['status'] = "fail";
                    $data['data'] = "";
                }
            }else{
                $data['msg'] = "数据错误，没有该经理";
                $data['status'] = "fail";
                $data['data'] = "";
            }

        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 经理奖金明细列表 cj
    function manager_push_money_list(){
        if ($_GET['id']){
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:3;
            $keyword = $_GET['keyword']?$_GET['keyword']:'';
            $arr =  $this->users_model->manager_push_money_list($_GET['id'],$page,$limit,$keyword);

            if(!$arr)
            {
                $arr = '';
            }
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 我的评分 cj
    function my_score(){
        if ($_GET['id'])
        {
            // 身份查询
            $m_info = $this->users_model->get_one($_GET['id']);
//            if(!$m_info['job_date'])
            if(1==1)
            {
                $entry_date = $m_info['entry_date'];
                $now_date = date("Y-m-d",time());
                $relax = [$entry_date];
                if($entry_date == $now_date)
                {
                    // 当天注册的
                    $relax[] = date("Y-m-d", strtotime("+1 months", strtotime($entry_date)));
                }
                while (strtotime($entry_date) < strtotime($now_date))
                {
                    $entry_date = date("Y-m-d", strtotime("+1 months", strtotime($entry_date)));
                    $relax[] = $entry_date;
                }
                // 取出倒数四个
                $use_arr = array_slice($relax,-4);
                $lenth = sizeof($use_arr);
                $nlen  = $lenth - 1;
                $result = [];
                while ($nlen > 0)
                {
                    $start_time = $use_arr[$nlen-1]." 00-00-00";
                    $end_time = date("Y-m-d", strtotime("-1 day", strtotime($use_arr[$nlen])))." 23-59-59";
                    $result[$start_time.','.$end_time] = $this->users_model->score_month_sum($start_time,$end_time,$_GET['id']);
                    $nlen--;
                }
                $res = '';
                $month = 0;
                $x = 0;
                foreach ($result as $k => $v)
                {
                    $month++;
                    $rr = up_to_standard($m_info['identity'],$v['total'],$month);
                    $res[$x]['status'] = $rr['status'];
                    $res[$x]['target'] = $rr['target'];
                    $res[$x]['score_sum'] = floatval($v['total']);
                    $res[$x]['fromto'] = $k;
                    if($res[$x]['target'] > $res[$x]['score_sum'])
                    {
                        $res[$x]['remain_score'] = floatval($res[$x]['target'] - $res[$x]['score_sum']);
                    }else{
                        $res[$x]['remain_score'] = 0;
                    }
                    $x++;
                }
                $sql = "select ifnull(sum(score),0) as total FROM score WHERE manager_id = ".$_GET['id'];
                $rtaotal = $this->db->query($sql)->row_array();
                $data['status'] = "success";
                $data['msg'] = "获取成功";
                $data['total'] = floatval($rtaotal['total']);
                $data['data'] = $res;

            }
//            else{
//                $data['msg'] = "已经转正，无需评分";
//                $data['status'] = "fail";
//                $data['data'] = "";
//            }
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 评分明细列表 cj
    function manager_score_list(){
        if ($_GET['id'] && $_GET['year'] && $_GET['month']){
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:3;

            $arr =  $this->users_model->manager_score_list($_GET['id'],$page,$limit,$_GET['year'],$_GET['month']);

            if(!$arr)
            {
                $arr = '';
            }
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 经理奖金详情 cj
    function manager_push_money_detail(){
        if ($_GET['id'] && $_GET['type']){
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:3;

            $arr =  $this->users_model->manager_push_money_detail($_GET['id'],$_GET['type']);

            if(!$arr)
            {
                $arr = '';
            }
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    //销售经理管理
    function manager_list(){
        if ($_GET['id']){
            $page = $_GET['page']?$_GET['page']:1;
            $sort_type = $_GET['sort_type']?$_GET['sort_type']:1;
            $sort_desc= $_GET['sort_desc']?$_GET['sort_desc']:1;
            $sort_desc= $_GET['sort_desc']?$_GET['sort_desc']:1;
            $limit = $_GET['limit']?$_GET['limit']:3;
            $arr =  $this->users_model->manager_list($_GET['id'],$_GET['status'],$sort_type,$sort_desc,$page,$limit,$_GET['search_text']);
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }


    //销售经理详情
    function manager_detail(){
        $page = $_GET['page']?$_GET['page']:1;
        $limit = $_GET['limit']?$_GET['limit']:3;
        $data=$this->users_model->manager_detail($_GET['id'],$_GET['pid'],$page,$limit);
        json_send($data);
    }

    function manager_money_by_month(){
        if($_GET['id']  && $_GET['pid'] && $_GET['month']){
            $arr =  $this->users_model->get_manager_money($_GET['id'],$_GET['pid'],$_GET["month"]);
            if (!$arr){$arr="";}
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    //销售经理榜单
    function manager_sort_list(){
        if ($_GET['id'] ){
            $type = $_GET['type'];// 榜单类型month按月 season按季
            $limit = $_GET['limit']?$_GET['limit']:3;   //榜单人数
            $arr =  $this->users_model->manager_sort_list($_GET['id'],$type,$limit);
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $arr;
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    //同步商城那边登录时间
    function login_to_app(){
        $post = $this->input->post();
        if ($post['app_customer_id'] && $post['login_time']){
            $bool = $this->db->where(array("id"=>$post['app_customer_id']))->update("customer",array("last_login"=>$post['login_time']));
            $row = $this->db->affected_rows();
            if ($row>0){
                $data['msg'] = "更新成功";
                $data['status'] = "success";
                $data['data'] = "";
            }else{
                $data['msg'] = "更新失败";
                $data['status'] = "fail";
                $data['data'] = "";
            }
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    //邀请页面
    function invite(){
        $mid = $_GET['mid'];
        $data['mid'] = $mid;
        $this->load->view('users/invite',$data);
    }
    //添加维护记录
    function add_manager_record(){
        $post = $this->input->post();
        if ($post['manager_id'] && $post['pid'] && $post['content']){
             $rs = $this->users_model->add_manager_record($post['manager_id'],$post['pid'] , $post['content']);
            if ($rs){
                $data['msg'] = "添加成功";
                $data['status'] = "success";
                $data['data'] = "";
            }else{
                $data['msg'] = "添加失败";
                $data['status'] = "fail";
                $data['data'] = "";
            }
        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 检测是否可以提请晋升
    function check_upgrade(){
        if($_GET['id'])
        {
            // 身份查询
            $m_info = $this->users_model->get_one($_GET['id']);
            if($m_info)
            {
                $res = check_upgrade($this->db,$_GET['id']);
                if($res)
                {
                    $data['data'] = $res;
                    $data['data']['now_identity'] = $m_info['identity'];
                    $data['data']['next_identity'] = next_identity($m_info['identity'])[0];
                    $data['status'] = "success";
                    $data['msg'] = "获取成功";
                }else{
                    $data['msg'] = "数据错误，请联系管理方";
                    $data['status'] = "fail";
                    $data['data'] = "";
                }
            }else{
                $data['msg'] = "数据错误，没有该经理";
                $data['status'] = "fail";
                $data['data'] = "";
            }

        }else{
            $data['msg'] = "参数错误";
            $data['status'] = "fail";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 获取当前版本号
    public function get_version()
    {
        $sql = "SELECT
                    *
                FROM
                    key_value
                WHERE
                    `key` = 'android' 
                OR `key` = 'ios' OR `key` = 'android_message'  OR `key` = 'ios_message' ";
        $rs = $this->db->query($sql)->result_array();
        $data['status'] = "success";
        $data['msg'] = "获取成功";
        $data['data'] = $rs;
        json_send($data);
    }


}